<template>
  <div>
    <div class="mt-6" v-loading="loading">
      <h3 class="text-lg">{{ $t("卡片属性") }}</h3>
      <el-card shadow="always" class="mt-5" >
        <span class="text-sm">{{ $t("卡片类型") }}</span>
        <div v-if="cardList.length > 0" class="mt-2">
          <div class="grid items-center justify-start grid-cols-4 gap-4 cardType" >
            <el-card :class="item.level_id == currentLevel.level_id ? 'selectedType' : ''" shadow="never" class="text-center cardTypeCard"
              @click="handleClick(item)" v-for="(item) of cardList" :key="item.level_id">
              {{ item.level_name }}
            </el-card>
          </div>
          <div class='flex flex-col items-start justify-start mt-5 cardNetwork'>
            <span class="mb-2 text-sm">{{ $t("卡片品牌") }}</span>
             <el-radio-group v-model="cardInfo.network" @change="handleChange">
                <el-radio :value="item.name" :label="item.name" v-for="(item) of currentLevel.network" :key="item.name" >
                  <template #default>
                    <img src="@/assets/images/card/Visa.png" alt="" class="cardImg" v-if="item.name == 'visa'">
                    <img src="@/assets/images/card/Master3.png" alt="" class="cardImg" v-else>
                  </template>
                </el-radio>
              </el-radio-group>
              <p class="mt-4 cardTips" v-if="online_scene.length">
                <el-tag type="info">
                  <span>{{$t('支持绑定')}}</span>
                  <p class="inline-block ml-4" v-if="pay_type == 'all'">
                    <img src="@/assets/images/card/GooglePay.png" alt="" class="inline-block mr-3 PayImg" >
                    <img src="@/assets/images/card/ApplePay.png" alt="" class="inline-block PayImg" >
                  </p>
                  <p class="inline-block ml-4" v-else>
                    <img v-if="pay_type == 'GooglePay'" src="@/assets/images/card/GooglePay.png" alt="" class="inline-block mr-3 PayImg" >
                    <img v-else src="@/assets/images/card/ApplePay.png" alt="" class="inline-block PayImg" >
                  </p>
                </el-tag></p>
          </div>
          <div class="mt-5 cardType">
            <p class="mb-2">{{ $t("卡片说明") }}</p>
            <el-card shadow="always" class="customCard">
              <div class="text-[#7F7F7F] pt-3">
                <p
                  v-html="currentLevel.description.replace(/\n/g, '<br>')"
                ></p>
              </div>
            </el-card>
          </div>
        </div>
      </el-card>
    </div>
    <div class="mt-6">
      <h3 class="text-lg">{{ $t("基本属性") }}</h3>
      <el-card class="mt-5" shadow="always">
        <el-form ref="createFormRef" label-position="top" :model="cardInfo" :rules="rules">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item :label="$t('充值金额')" prop="total_amount">
                <template #label>
                  <p class="flex items-center justify-start">
                    {{ $t("充值金额") }}
                    <el-tooltip class="box-item" effect="light" :content="$t('开卡时想要充入的额度（金额）')" placement="right">
                      <el-icon class="ml-1" color="#3853ED">
                        <QuestionFilled />
                      </el-icon>
                    </el-tooltip>
                  </p>
                </template>
                <el-input v-model="cardInfo.total_amount" :placeholder="$t('卡-请输入充值金额')"
                  class="input-with-select customInput" @input="handleTotalAmountChange" size="large" type="number">
                  <template #append>
                    <el-select v-model="cardInfo.currency" :placeholder="$t('币种')" @change="handleCurrencyChange"
                      style="width: 115px" size="large">
                      <el-option v-for="item in state.cardsCurrencyList" :key="item.currency" :label="item.currency"
                        :value="item.currency">
                      </el-option>
                    </el-select>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('卡片别名')" prop="nick_name">
                <template #label>
                  <p class="flex items-center justify-start">
                    {{ $t("卡片别名") }}
                    <el-tooltip class="box-item" effect="light" :content="$t('请您设定您的卡片昵称')" placement="right">
                      <el-icon class="ml-1" color="#3853ED">
                        <QuestionFilled />
                      </el-icon>
                    </el-tooltip>
                  </p>
                </template>
                <el-input v-model="cardInfo.nick_name" size="large" :placeholder="$t('请输入卡别名')"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item :label="$t('姓氏')" prop="last_name">
                <el-input v-model="cardInfo.last_name" size="large" :placeholder="$t('请输入姓氏')"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('名字')" prop="first_name">
                <el-input v-model="cardInfo.first_name" size="large" :placeholder="$t('请输入名字')"></el-input>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item :label="$t('手机号')" prop="mobile">
                <el-input v-model="cardInfo.mobile" :placeholder="$t('输入手机号码')" size="large" type="number"
                  class="customInput">
                  <template #prepend>
                    <el-input class="customInputWrap" v-model="cardInfo.area_code" :placeholder="$t('区号')"
                      style="width:112px;max-width:120px" size="large" type="number">
                    </el-input>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('邮箱')" prop="email">
                <el-input v-model="cardInfo.email" size="large" :placeholder="$t('请输入邮箱地址')"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </div>
    <div class="mt-6">
      <h3 class="mb-5 text-lg">{{ $t("扣款方式") }}</h3>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-card>
            <el-row :gutter="30">
              <el-col :span="12">
                <div class="detailRow">
                  <p class="rowName">{{ $t("资产余额") }}</p>
                  <p class="rowValue">
                   <el-select v-model="state.currencyInfo" class="customSelect" @change="selectBalance" v-if="state.currencyList.length>1">
                          <el-option
                            v-for="item in state.currencyList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                          />
                      </el-select>
                      <p v-else>{{ state.currencyInfo }}</p>
                  </p>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="detailRow">
                  <p class="rowName">{{ $t("手续费") }}</p>
                  <p class="rowValue">
                    {{ cardInfo.total_amount ? state.fee : 0}} {{ state.currency }}
                  </p>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="30">
              <el-col :span="12">
                <div class="detailRow">
                  <p class="rowName">{{ $t("消耗金额") }}</p>
                  <!-- 输入的总额度 + 总额度*费率*币种价格 -->
                  <p class="rowValue">
                      {{
                        cardInfo.asset_type == "balance"
                          ? truncateDecimals(
                              state.totalPrice,
                              2
                            )
                          : truncateDecimals(
                              state.totalPrice,
                              8
                            )
                      }}
                      {{ state.currency }}
                    </p>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="detailRow">
                  <p class="rowName">
                    {{ $t("年费") }}{{ currentLevel.year_fee_discount < 1 ? `(${ (currentLevel.year_fee_discount * 100).toFixed(0)}% ${$t("折扣")})` : '' }}</p>
                  <p class="rowValue">
                    <span v-if="currentLevel">{{ currentLevel.year_fee }} 
                      {{ state.currency }}</span>
                    <span v-else>--</span>
                  </p>
                </div>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>
      <div class="flex items-center justify-center">
        <div size="large" type="danger" class="h-10 mt-10 w-36 btn" @click="addCardSave(createFormRef)" v-loading="btnLoading">
          {{ $t("创建卡片") }}
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, computed, watch } from "vue";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import {
  AddCard,
  GetCardsConfig,
  GetCardsBalance,
  GetCardsPrice,
  GetCardsCurrency,
  getCardLevel
} from "@/api/card";
import { ElMessage } from "element-plus";
import { truncateDecimals } from "@/utils/utils";
const router = useRouter();

const createFormRef = ref(null);
const loading = ref(false);
const btnLoading = ref(false);

const cardList = ref([])

const state = reactive({
  asset_type: "balance",
  cardType: [],
  balanceInfo: [], //余额
  coinsInfo: [], //授信
  totalPrice: 0,
  price: 0, // 选择币种价格
  card_rate: 0, // 汇率
  fee:0,
  currencyType: "currency", //货币类型
  currencyList: [],
  currencyInfo: "",
  currency: "",
});

const cardInfo = reactive({
  category_id: "",
  total_amount: "",
  nick_name: "",
  first_name: "",
  mobile: "",
  email: "",
  currency: "",
  asset_type: "balance",
  last_name: "",
  asset_currency: "",
  network:'',
});

const pay_type = ref('all')
const online_scene = ref([])

const props = defineProps({
    cardTypeInfo: {
        type: Object,
        default:()=>{}
    },
    balanceInfo: {
        type: Object,
        default:()=>[]
    },
    coinsInfo: {
        type: Object,
        default:()=>[]
    }
})
const currentLevel = ref({})
const handleClick = (item) => {
  currentLevel.value = item;
  cardInfo.network = item.network[0]?.name;
  online_scene.value = item.network[0]?.online_scene;
  // 卡片品牌下的支付绑定
  if (online_scene.value.length >= 2) { 
    pay_type.value = "all"
  } else {
    pay_type.value = online_scene.value[0] == 'GooglePay' ? 'GooglePay' :'ApplePay'
  }
  state.fee = (Number(cardInfo.total_amount) * (Number(currentLevel.value.card_rate) + Number(currentLevel.value.in_rate))) + Number(currentLevel.value.card_fee) + Number(currentLevel.value.in_fee) || 0;
  // 输入的总额度+手续费+年费
  let price = Number(cardInfo.total_amount) + Number(currentLevel.value.year_fee* currentLevel.value.year_fee_discount) + state.fee;
  state.totalPrice = price;
};

const cardInformation = async()=>{
      // 判断如果扣款方式为balance，则取他相应的资产列表
  if (props.cardTypeInfo.asset_type == "balance") {
    state.currencyList = [];
    if (props.balanceInfo.length > 0) {
      state.currencyList = props.balanceInfo.map((item) => {
        return {
          label: item.amount + " " + item.currency,
          value: item.amount + " " + item.currency,
        };
      });
    }
  }
  // 判断如果扣款方式为crypto，则取他相应的资产列表（coins）
  if (props.cardTypeInfo.asset_type == "crypto") {
    state.currencyList = [];
    if (props.coinsInfo.length > 0) {
      state.currencyList = props.coinsInfo.map((item) => {
        return {
          label: item.amount + " " + item.currency,
          value: item.amount + " " + item.currency,
        };
      }); // 币种选项
    }
  }
  await getCardsCurrency(); // 获取卡片币种
  if (props.cardTypeInfo.asset_type == "balance" && props.balanceInfo.length > 0) {
    amountInfo(props.balanceInfo);
  }
  if (props.cardTypeInfo.asset_type == "crypto" && props.coinsInfo.length > 0) {
    amountInfo(props.coinsInfo);
  }
  // 默认选用第一个币种
  // const currency = state.currencyInfo.split(" ")[1] || "";
  // await getCardPrice(currency, true); // 获取币种金额，即下方资产下拉，多条展示下拉，一条不展示下拉
}

const getCardLevelList = async () => {
  loading.value = true;
  try {
    const res = await getCardLevel()
    cardList.value = res.card_level || []
    currentLevel.value = res.card_level[0];
    cardInfo.network = currentLevel.value.network[0].name;
    online_scene.value = currentLevel.value.network[0].online_scene;
    // 卡片品牌下的支付绑定
    if (online_scene.value.length >= 2) { 
      pay_type.value = "all"
    } else {
      pay_type.value = online_scene.value[0] == 'GooglePay' ? 'GooglePay' :'ApplePay'
    }
    let price = Number(cardInfo.total_amount) + Number(currentLevel.value.year_fee * currentLevel.value.year_fee_discount) + state.fee;
    state.totalPrice = price;
    loading.value = false
  } catch {
    loading.value = false
  }
}

onMounted(async () => {
  await getCardLevelList()
  await cardInformation()
})

// 邮箱验证
const checkEmail = (rule, value, callback) => {
  if (!value) {
    return callback(new Error(t("邮箱不能为空")));
  } else {
    const emailRegExp =
      /^([a-zA-Z0-9_\.-]+)@([\da-zA-Z\.-]+)\.([a-zA-Z\.]{2,6})$/;
    if (emailRegExp.test(value)) {
      callback();
    } else {
      return callback(new Error(t("请输入正确的邮箱")));
    }
  }
};


// 卡额度验证，必须大于1
const checkTotalAmount = (rule, value, callback) => {
  if (!value) {
    return callback(new Error(t("卡-请输入充值金额")));
  } else {
    let money = Number(cardInfo.total_amount) * state.price;
    if (value <= 1) {
      return callback(new Error(t("卡片额度必须大于1")));
    } else if (money > Number(state.currencyInfo.split(" ")[1])) {
      return callback(
        new Error(`${t("扣款币种")} ${state.currency} ${t("余额不足")}`)
      );
    } else {
      callback();
    }
  }
};

// 规则验证
const rules = reactive({
  total_amount: [
    { required: true, message: t("卡-请输入充值金额"), trigger: "blur" },
    { validator: checkTotalAmount, trigger: "blur" },
  ],
  nick_name: [
    { required: true, message: t("请输入卡片别名"), trigger: "blur" },
  ],
  last_name: [
    { required: true, message: t("请输入姓氏"), trigger: "blur" },
  ],
  first_name: [
    { required: true, message: t("请输入名字"), trigger: "blur" },
  ],
  mobile: [
    { required: true, message: t("请输入手机号"), trigger: "blur" },
    { min: 6, max: 16, message: t("请输入6-16位的数字"), trigger: "blur" },
  ],
  email: [
    { required: true, message: t("请输入邮箱"), trigger: "blur" },
    { validator: checkEmail, trigger: "change" },
  ],
});

// 选择资产
// const selectBalance = async (val) => {
//   // const currency = val.split(" ")[1] || "";
//   // getCardPrice(currency); // 获取币种价格
// };

// 获取资产模块数据
const amountInfo = (info) => {
  let amountInfo = [];
  // 根据资产类型使用对应列表数据，默认选中第一条数据
  amountInfo = info.filter((item) => {
    if (item.currency === cardInfo.currency) {
      return item;
    }
  });
  // 默认第一条
  state.currencyInfo =
    amountInfo.length < 1
      ? `${info[0].amount} ${info[0].currency} `
      : `${amountInfo[0].amount} ${amountInfo[0].currency}`;
  state.currency = state.currencyInfo.split(" ")[1] || "";
};

// 选择币种
const handleCurrencyChange = async (val) => {
  // 选择币种切换下方资产数据
  const { balance, coins } = await GetCardsBalance();
  if (balance.length > 0) {
    amountInfo(balance);
  } else {
    amountInfo(coins);
  }
};

// // 获取币种价格
// const getCardPrice = async (currency, isTrue) => {
//   if (cardInfo.currency) {
//     let query = {
//       from_currency: cardInfo.currency, //币种
//       to_currency: currency,
//       to_type: props.cardTypeInfo.asset_type == "balance" ? "currency" : "coin", //根据资产类型判断穿什么字段
//     };
//     try {
//       const { price } = await GetCardsPrice(query);
//       state.price = price;
//       state.currency = state.currencyInfo.split(" ")[1] || ""; // 汇率后方的币种

//       // 初始化进来不校验
//       if (!isTrue && cardInfo.total_amount !== "") {
//         createFormRef.value.validateField("total_amount");
//       }
//       // 总额度*汇率 虚拟资产保留6位小数,货币资产保留2位小数
//       if (cardInfo.total_amount !== "") {
//         state.totalPrice =
//           (cardInfo.total_amount * state.price) +
//           (cardInfo.total_amount * state.card_rate *
//             state.price) || 0;
//       } else {
//         state.totalPrice = 0;
//       }
//     } catch {
//       loading.value = false;
//     }
//   }
// };

// 输入卡额度
const handleTotalAmountChange = (val) => {
  let index = val.indexOf("."); // 只能输入正整数
  if (index) {
    cardInfo.total_amount = cardInfo.total_amount.split(".")[0];
  } else {
    cardInfo.total_amount = val;
  }
  // 输入的开卡金额 * (card_rate + in_rate) + card_fee + in_fee
  state.fee = val ? (Number(val) * (Number(currentLevel.value.card_rate) + Number(currentLevel.value.in_rate))) + Number(currentLevel.value.card_fee) + Number(currentLevel.value.in_fee) : 0;
  // 输入的总额度+手续费+年费
  let price = Number(val) + Number(currentLevel.value.year_fee * currentLevel.value.year_fee_discount) + state.fee;
  state.totalPrice = price;
};


const handleChange = (val) => {
  console.log(val,currentLevel,'val')
  let list = currentLevel.value.network
  let result = list.find(item => item.name == val)
  online_scene.value = result.online_scene
   // 卡片品牌下的支付绑定
  if (online_scene.value.length >= 2) { 
    pay_type.value = "all"
  } else {
    pay_type.value = online_scene.value[0] == 'GooglePay' ? 'GooglePay' :'ApplePay'
  }
}

// 创建卡片
const addCardSave = (formRef) => {
  if (!formRef) return;
  formRef.validate(async (valid, fields) => {
    if (valid) {
      if (!props.cardTypeInfo.category_id) {
        ElMessage.error(t("请选择卡类型"));
      } else {
        if (!cardInfo.area_code) {
          ElMessage.error(t("请填写区号"));
        } else {
          try {
            btnLoading.value = true;
            cardInfo.asset_currency = state.currency || '';
            cardInfo.level_id = currentLevel.value.level_id
            cardInfo.category_id = props.cardTypeInfo.category_id
            console.log(cardInfo, "cardInfo");
            const data = await AddCard(cardInfo);
            btnLoading.value = false;
            ElMessage({
              type: "success",
              message: data.offline
                ? t(
                  "卡片创建成功，进入审核阶段，审核通过后将激活卡片并可以进行使用"
                )
                : t("创建卡片成功"),
            });
            router.replace({
              path: "/card/management",
            });
          } catch {
            btnLoading.value = false;
          }
        }
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 获取币种，默认选中第一条
const getCardsCurrency = async () => {
  try {
    const { cards_currency } = await GetCardsCurrency({
      category_id: props.cardTypeInfo.category_id,
    });
    state.cardsCurrencyList = cards_currency;
    cardInfo.currency = state.cardsCurrencyList[0].currency;
  } catch { }
};

const lsLocale = localStorage.getItem("locale") || "";
const currentLanguage = ref("");
if (lsLocale) {
  currentLanguage.value = JSON.parse(lsLocale)?.locale;
}
import { useLocaleStore } from "@/store/modules/locales";

const useLocale = useLocaleStore();

watch(
  () => useLocale.locale,
  async (val) => {
    await getCardLevelList()
    await cardInformation()
  }
);

</script>
<style lang="scss" scoped>
.detailRow {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 0.5rem;

  .rowName {
    min-width: 30%;
    flex-shrink: 0;
    display: inline-block;
  }

  .selectName {
    min-width: 10%;
    text-align: center;
    flex-shrink: 0;
    display: inline-block;
  }

  .rowValue {
    display: inline-block;
    word-break: break-all;
    text-align: right;
  }
}

.hoverStyle:hover {
  background-color: #f4e1e1;
  border-radius: 5px;
}

.active {
  background-color: #ebc9c9;
  border-radius: 5px;
}

.btn {
  text-align: center;
  line-height: 40px;
  background: #e54c5f;
  border-radius: 5px;
  color: #fff;
  cursor: pointer;
}

.selectIcon {
  color: #e54c5f;
  font-size: 24px;
}

.selectedType {
  border: 1px solid #e54c5f;
  background-color: #e54c5f;
  color: #fff;
  border-radius: 5px;
}

.cardType{
  width: 60%
}

.cardNetwork{
  .cardImg{
    width: 80px;
    height:40px;
    object-fit: contain;
  }
  .cardImg1{
    width: 90px;
    // height:50px;
    object-fit: contain;
  }
  .PayImg{
    width: 35px;
    height:30px;
    object-fit: contain;
  }
  .el-tag{
    height:30px;
    color:#000
  }
}

@media screen and (max-width: 980px) {
 .cardType{
    width:100%
 }
}

@media screen and (max-width: 768px) {
 .cardType{
    width:100%
 }
}
</style>